package threadSafe.property;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang.StringUtils;

public class Count {
	/*
	 * 多线程操作此num是线程不安全的
	 */
	private static int num;
	/*
	 * 线程不安全
	 */
	private static AtomicInteger nums = new AtomicInteger(0);
	/*不安全*/
	private  AtomicInteger numss = new AtomicInteger(0);
	
	private  int numsss;
	
	private static Map<Integer,String> userconnections = new HashMap<Integer,String>();
	
	public static  void count() { 
		for (int i = 1; i <= 10; i++) {
			num += i;
		}
		System.out.println(Thread.currentThread().getName() + "总数-:55-" + num);
	}
	
	public static  void countAtomic() { 
		for (int i = 1; i <= 10; i++) {
			nums.incrementAndGet();
		}
		System.out.println(Thread.currentThread().getName() + "总数=:55-" + nums);
	}
	
	public void countAtomicss() { 
		for (int i = 1; i <= 10; i++) {
			numss.incrementAndGet();
		}
		System.out.println(Thread.currentThread().getName() + "总数=:10-" + numss);
	}
	public void counts() { 
		for (int i = 1; i <= 10; i++) {
			numsss += i;
		}
		System.out.println(Thread.currentThread().getName() + "总数-:55-" + numsss);
	}
	
	
	public static boolean getSameSessionUserNameStr(String user) throws InterruptedException{
		Set<Integer> keySet = userconnections.keySet();
		String username = StringUtils.split(user, "#@#")[0];
		String sessionId = StringUtils.split(user, "#@#")[1];
		synchronized(keySet){
		for (Integer conn : keySet) {
			
				String cuser = userconnections.get(conn);
				String a = "";
				for(int i=0,n=cuser.length();i<n ;i++){
					a += cuser.charAt(i)+""; 
					System.out.println(Thread.currentThread().getName() +a); 
				} 
				userconnections.put(conn,a); 
			}
		} 
		return true;
	}
	public static void addUser(String user, Integer conn){
		userconnections.put(conn,user);	//添加连接
	}
}